<?php

/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

use app\controller\home\Index;
use core\lib\tool\Token;
use Webman\Http\Request;
use Webman\Route;


/**
 * 首页
 */
Route::any('/', [Index::class, 'index']);


Route::fallback(function (Request $request) {
    if (!$request->expectsJson()) {
        return view('/template/404', ['error' => 'some error'])->withStatus(404);
    }
});


Route::any('/component/[{path:.+}]', function (Request $request, $path = '') {

    //安全检查 只允许静态文件
    $pathinfo = pathinfo($path);
    if (!in_array(strtolower($pathinfo['extension']), ['css', 'js', 'otf', 'woff2', 'woff', 'ttf', 'png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'bmp'])) {
        return response('<h1>404 Not Found</h1>', 404);
    }


    // 静态文件目录
    $static_base_path = base_path() . '/component';
    // 安全检查，避免url里 /../../../password 这样的非法访问
    if (strpos($path, '..') !== false) {
        return response('<h1>400 Bad Request</h1>', 400);
    }
    // 文件
    $file = $static_base_path . '/' . $path;
    if (!is_file($file)) {

        return response('<h1>404 Not Found</h1>', 404);
    }
    return response('')->withFile($file);
});

/**
 * 元素
 */
Route::any('/element/[{path:.+}]', function (Request $request, $path = '') {

    $reflectionClass = new ReflectionClass('component\\element\\' . get_element() . '\\controller\\' . get_controller());
    $method = $reflectionClass->getMethod(get_action());
    if ($method->isPublic() && $method != 'index') {

        $instance = $reflectionClass->newInstance();
        return $method->invoke($instance);
    }


    return response('<h1>404 Not Found</h1>', 404);
});


Route::any('/ant_shielding_url/{path}', function (Request $request, $path = '') {
    return response('')->withFile(public_path()  . base64_decode($path));
});
